<template>
  <div class="member-manage-container">
    <h2  >会员管理</h2>

    <!-- 搜索区域 -->
    <div class="search-container" style="margin: 0 20px 20px; padding: 15px; border: 1px solid #e6e6e6; border-radius: 8px;">
      <el-input
          v-model="searchName"
          placeholder="请输入会员姓名"
          style="width: 200px; margin-right: 10px;"
          clearable
          @keyup.enter="handleSearch"
      />
      <el-input
          v-model="searchPhone"
          placeholder="请输入手机号"
          style="width: 200px; margin-right: 10px;"
          clearable
          @keyup.enter="handleSearch"
      />

      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset" style="margin-left: 10px;">重置</el-button>
      <el-button type="success" @click="openAddDialog" style="margin-left: 20px;">新增会员</el-button>
    </div>

    <!-- 会员列表 -->
    <div style="margin: 0 20px;">
      <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%;"
      >
<!--        <el-table-column label="ID" prop="id" width="80" align="center" />-->
        <el-table-column label="会员姓名" prop="name" align="center"/>
        <el-table-column label="手机号" prop="phone" align="center"/>
        <el-table-column label="账户余额" prop="balance" align="center">
          <template #default="scope">{{ Number(scope.row.balance).toFixed(2) }}元</template>
        </el-table-column>
        <el-table-column label="会员积分" prop="points" align="center" />
        <el-table-column label="会员状态" prop="status" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdTime" align="center">
          <template #default="scope">{{ formatDate(scope.row.createdTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="380" align="center">
          <template #default="scope">
<!--            <el-button-->
<!--                type="primary"-->
<!--                size="small"-->
<!--                @click="openEditDialog(scope.row)"-->
<!--                :disabled="scope.row.status === '已注销'"-->
<!--            >-->
<!--              编辑-->
<!--            </el-button>-->
            <el-button
                type="warning"
                size="small"
                @click="openRechargeDialog(scope.row)"
                style="margin-left: 8px;"
                :disabled="scope.row.status === '已注销'"
            >
              充值
            </el-button>
            <el-button
                type="info"
                size="small"
                @click="openExchangeDialog(scope.row)"
                style="margin-left: 8px;"
                :disabled="scope.row.status === '已注销'"
            >
              积分兑换
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="openCancelMemberDialog(scope.row)"
                style="margin-left: 8px;"
                :disabled="scope.row.status === '已注销'"
            >
              退会员
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 15px; text-align: right;">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog title="会员信息" v-model="isMemberDialogOpen" width="500px">
      <el-form :model="memberForm" :rules="memberRules" ref="memberFormRef" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="memberForm.name" placeholder="请输入会员姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="memberForm.phone" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>
<!--        <el-form-item label="会员状态" v-if="isEdit">-->
<!--          <el-select v-model="memberForm.status" disabled>-->
<!--            <el-option label="正常" value="正常" />-->
<!--            <el-option label="已注销" value="已注销" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <el-button @click="isMemberDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="submitMemberForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 充值弹窗 -->
    <el-dialog title="会员充值" v-model="isRechargeDialogOpen" width="400px">
      <el-form :model="rechargeForm" :rules="rechargeRules" ref="rechargeFormRef" label-width="100px">
        <el-form-item label="会员姓名" disabled>
          <el-input v-model="rechargeForm.name" />
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model="rechargeForm.amount" placeholder="请输入充值金额" type="number" step="0.01" min="0.01" />
        </el-form-item>
        <el-form-item label="规则" class="text-info">
          充100送10，1元=1积分
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isRechargeDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="submitRechargeForm">确认充值</el-button>
      </template>
    </el-dialog>

<!--    &lt;!&ndash; 积分兑换弹窗 &ndash;&gt;-->
<!--    <el-dialog title="积分兑换" v-model="isExchangeDialogOpen" width="400px">-->
<!--      <el-form :model="exchangeForm" :rules="exchangeRules" ref="exchangeFormRef" label-width="100px">-->
<!--        <el-form-item label="会员姓名" disabled>-->
<!--          <el-input v-model="exchangeForm.name" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="当前积分" disabled>-->
<!--          <el-input v-model="exchangeForm.currentPoints" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="兑换积分" prop="exchangePoints">-->
<!--          <el-input v-model="exchangeForm.exchangePoints" placeholder="请输入兑换积分" type="number" min="1" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="规则" class="text-info">-->
<!--          1积分=0.1元，兑换后余额增加-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <template #footer>-->
<!--        <el-button @click="isExchangeDialogOpen = false">取消</el-button>-->
<!--        <el-button type="primary" @click="submitExchangeForm">确认兑换</el-button>-->
<!--      </template>-->
<!--    </el-dialog>-->
    <!-- 积分兑换弹窗 -->
    <el-dialog title="积分兑换" v-model="isExchangeDialogOpen" width="400px">
      <el-form :model="exchangeForm" :rules="exchangeRules" ref="exchangeFormRef" label-width="100px">
        <el-form-item label="会员姓名" disabled>
          <el-input v-model="exchangeForm.name" />
        </el-form-item>
        <el-form-item label="当前积分" disabled>
          <el-input v-model="exchangeForm.currentPoints" />
        </el-form-item>
        <!-- 新增：兑换积分输入框+全部兑换按钮 -->
        <el-form-item label="兑换积分" prop="exchangePoints">
          <div style="display: flex; gap: 8px;">
            <el-input
                v-model="exchangeForm.exchangePoints"
                placeholder="请输入兑换积分"
                type="number"
                min="1"
                style="flex: 1;"
            />
            <el-button
                type="primary"
                size="small"
                @click="handleExchangeAll"
            >
              全部积分
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="规则" class="text-info">
          1积分=0.1元，兑换后余额增加
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isExchangeDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="submitExchangeForm">确认兑换</el-button>
      </template>
    </el-dialog>

    <!-- 退会员弹窗（新增） -->
    <el-dialog title="退会员确认" v-model="isCancelMemberDialogOpen" width="400px">
      <el-form :model="cancelMemberForm" label-width="100px">
        <el-form-item label="会员姓名" disabled>
          <el-input v-model="cancelMemberForm.name" />
        </el-form-item>
        <el-form-item label="手机号" disabled>
          <el-input v-model="cancelMemberForm.phone" />
        </el-form-item>
        <el-form-item label="当前余额" disabled>
          <el-input v-model="cancelMemberForm.balance" suffix="元" />
        </el-form-item>
        <el-form-item label="当前积分" disabled>
          <el-input v-model="cancelMemberForm.points" suffix="分" />
        </el-form-item>
        <el-form-item label="退会员说明" class="text-danger">
          退会员后，账户余额和积分将清零，会员状态变为"已注销"，不可恢复！
        </el-form-item>
        <el-form-item label="确认操作" prop="confirm">
          <el-checkbox v-model="cancelMemberForm.confirm">我已确认退会员操作</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isCancelMemberDialogOpen = false">取消</el-button>
        <el-button type="danger" @click="submitCancelMember">确认退会员</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/axios/http'

// 简化：不用复杂的reactive，直接用ref
const searchName = ref('')
const searchPhone = ref('')
const searchStatus = ref('') // 新增：状态搜索
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])

// 弹窗控制（用v-model绑定，更稳定）
const isMemberDialogOpen = ref(false) // 新增/编辑
const isRechargeDialogOpen = ref(false) // 充值
const isExchangeDialogOpen = ref(false) // 兑换
const isCancelMemberDialogOpen = ref(false) // 退会员（新增）
// 全部兑换：自动填充当前可用积分
const handleExchangeAll = () => {
  // 直接将当前积分赋值给兑换积分输入框
  exchangeForm.value.exchangePoints = exchangeForm.value.currentPoints
}
// 表单数据
const memberFormRef = ref(null)
const memberForm = ref({
  id: '',
  name: '',
  phone: '',
  balance: 0,
  points: 0,
  status: '正常' // 新增：会员状态（正常/已注销）
})
const memberRules = ref({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' }
  ]
})
const isEdit = ref(false) // 是否编辑模式

const rechargeFormRef = ref(null)
const rechargeForm = ref({
  id: '',
  name: '',
  amount: ''
})
const rechargeRules = ref({
  amount: [{ required: true, message: '请输入充值金额', trigger: 'blur' }]
})

const exchangeFormRef = ref(null)
const exchangeForm = ref({
  id: '',
  name: '',
  currentPoints: 0,
  exchangePoints: ''
})
const exchangeRules = ref({
  exchangePoints: [
    { required: true, message: '请输入兑换积分', trigger: 'blur' },
    {
      validator: (rule, val, cb) => {
        if (val > exchangeForm.value.currentPoints) {
          cb(new Error('积分不足'))
        } else {
          cb()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 退会员表单（新增）
const cancelMemberForm = ref({
  id: '',
  name: '',
  phone: '',
  balance: 0,
  points: 0,
  confirm: false // 确认勾选
})
const cancelMemberRules = ref({
  confirm: [{ required: true, message: '请确认退会员操作', trigger: 'change' }]
})

// 页面加载时查询列表
onMounted(() => {
  getMemberList()
})

// 查询会员列表（修改：增加状态筛选）
const getMemberList = async () => {
  try {
    const res = await http.post('/glsb/get_member_by', {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      name: searchName.value,
      phone: searchPhone.value,
      status: searchStatus.value // 新增：状态筛选参数
    })
    if (res.data.result === 'success') {
      tableData.value = res.data.data.list || []
      total.value = res.data.data.total || 0
    } else {
      ElMessage.error('查询失败：' + res.data.msg)
    }
  } catch (err) {
    ElMessage.error('网络错误，请检查接口')
    console.error(err)
  }
}

// 搜索按钮
const handleSearch = () => {
  pageNum.value = 1
  getMemberList()
}

// 重置按钮
const handleReset = () => {
  searchName.value = ''
  searchPhone.value = ''
  searchStatus.value = '' // 新增：重置状态搜索
  pageNum.value = 1
  getMemberList()
}

// 分页改变
const handleSizeChange = (val) => {
  pageSize.value = val
  getMemberList()
}
const handleCurrentChange = (val) => {
  pageNum.value = val
  getMemberList()
}

// 新增会员
const openAddDialog = () => {
  isEdit.value = false
  memberForm.value = { id: '', name: '', phone: '', balance: 0, points: 0, status: '正常' }
  isMemberDialogOpen.value = true
}

// 编辑会员
const openEditDialog = (row) => {
  isEdit.value = true
  memberForm.value = { ...row } // 直接复制数据（包含status）
  isMemberDialogOpen.value = true
}

// 提交新增/编辑
const submitMemberForm = async () => {
  try {
    await memberFormRef.value.validate()
    let res
    if (isEdit.value) {
      res = await http.post('/glsb/modify_memberby_id', memberForm.value)
    } else {
      res = await http.post('/glsb/add_one_member', memberForm.value)
    }
    if (res.data.result === 'success') {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      isMemberDialogOpen.value = false
      getMemberList()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (err) {
    ElMessage.error('表单校验失败')
    console.error(err)
  }
}

// 充值
const openRechargeDialog = (row) => {
  rechargeForm.value = { id: row.id, name: row.name, amount: '' }
  isRechargeDialogOpen.value = true
}

// 提交充值
const submitRechargeForm = async () => {
  try {
    await rechargeFormRef.value.validate()
    // 关键修复：将amount转为字符串传递，避免后端Integer转BigDecimal错误
    const res = await http.post('/glsb/member_recharge', {
      id: rechargeForm.value.id,
      amount: rechargeForm.value.amount.toString() // 转为字符串
    })
    if (res.data.result === 'success') {
      ElMessage.success('充值成功')
      isRechargeDialogOpen.value = false
      getMemberList()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (err) {
    ElMessage.error('充值失败')
    console.error(err)
  }
}

// 积分兑换
const openExchangeDialog = (row) => {
  exchangeForm.value = {
    id: row.id,
    name: row.name,
    currentPoints: row.points,
    exchangePoints: ''
  }
  isExchangeDialogOpen.value = true
}

// 提交兑换
const submitExchangeForm = async () => {
  try {
    await exchangeFormRef.value.validate()
    const res = await http.post('/glsb/member_exchange', {
      id: exchangeForm.value.id,
      points: Number(exchangeForm.value.exchangePoints)
    })
    if (res.data.result === 'success') {
      ElMessage.success('兑换成功')
      isExchangeDialogOpen.value = false
      getMemberList()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (err) {
    ElMessage.error('兑换失败')
    console.error(err)
  }
}

// 打开退会员弹窗（新增）
const openCancelMemberDialog = (row) => {
  cancelMemberForm.value = {
    id: row.id,
    name: row.name,
    phone: row.phone,
    balance: Number(row.balance).toFixed(2),
    points: row.points,
    confirm: false
  }
  isCancelMemberDialogOpen.value = true
}

// 提交退会员（新增）
const submitCancelMember = async () => {
  try {
    // 校验是否勾选确认
    if (!cancelMemberForm.value.confirm) {
      return ElMessage.warning('请勾选确认退会员操作')
    }

    // 二次确认
    await ElMessageBox.confirm(
        '确定要为该会员办理退卡吗？退卡后余额和积分将清零，状态变为已注销，不可恢复！',
        '退会员确认',
        {
          type: 'danger',
          confirmButtonText: '确认退卡',
          cancelButtonText: '取消'
        }
    )

    // 调用退会员接口
    const res = await http.post('/glsb/cancel_member', {
      id: cancelMemberForm.value.id
    })

    if (res.data.result === 'success') {
      ElMessage.success('退会员成功')
      isCancelMemberDialogOpen.value = false
      getMemberList()
    } else {
      ElMessage.error('退会员失败：' + res.data.msg)
    }
  } catch (err) {
    if (err.message !== 'cancel') {
      ElMessage.error('退会员失败')
      console.error(err)
    }
  }
}

// 删除会员（隐藏，保留代码）
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该会员吗？', '提示', {
      type: 'warning'
    })
    const res = await http.post('/glsb/remove_memberby_id', { id })
    if (res.data.result === 'success') {
      ElMessage.success('删除成功')
      getMemberList()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (err) {
    if (err.message !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(err)
    }
  }
}

// 日期格式化
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  return new Date(Number(timestamp)).toLocaleString('zh-CN')
}
</script>

<style scoped>
.member-manage-container {
  padding: 20px;
}
.search-container {
  background: #f9f9f9;
}
/* 退会员弹窗样式 */
.el-dialog__body .text-danger {
  color: #f56c6c;
  font-size: 13px;
  margin-top: 5px;
}
.el-tag {
  font-size: 12px;
  padding: 2px 8px;
}
</style>